package com.main.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

/**
 * @author admin
 * @date 2019/05/20
 */
@RequestMapping(value = "fileController")
@Controller
public class FileController {

    @RequestMapping(value = "uploadFile", method = RequestMethod.POST)
    public String uploadFile(HttpServletRequest request, @RequestParam(value = "filedesc", required = false) String fileDesc, @RequestParam(value = "uploadFile") MultipartFile file, Model model) {

        if (!file.isEmpty()) {
            System.out.println("文件正确");
            String path = request.getContextPath();
            System.out.println("路径为:" + path);
            /*文件原始名称*/
            String fileName = file.getOriginalFilename();
            File newFile = new File(path, fileName);
            if (!newFile.getParentFile().exists()) {
                newFile.getParentFile().mkdirs();
            }
            try {
                path = "F:" + File.separator + "测试文件夹";
                file.transferTo(new File(path + File.separator + fileName));
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.out.println("保存成功");
            model.addAttribute("result", "储存成功");
        } else {
            model.addAttribute("result", "储存失败");
            System.out.println("文件错误");
        }
        return "/fileupload/uploadresult";

    }


}
